package com.scau.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scau.dao.CommentDao;
import com.scau.pojo.Message;
import com.scau.service.CommentService;
import com.scau.service.MessageService;

@RestController
@RequestMapping("/messageController")
public class MessageController{

	@Autowired
	MessageService messageService;
	
	@Autowired
	CommentService commentService;
	
	@Autowired
	CommentDao commentDao;
	
	@RequestMapping("/queryAllMessage")
	public List<Message> query() {
		return messageService.query();
	}
	
	@RequestMapping("/editMessage")
	public int edit(@RequestBody JSONObject jsonObject) throws Exception{
		int result=0;
		try{
			result=messageService.update(jsonObject);
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		return result;
	}
	
	@RequestMapping("/queryMessagesBySeId")
	public List<Message> queryMessagesBySeId(@RequestParam int seId){
		List<Message> messageList=messageService.queryBySeId(seId);
		return messageList;
	}
	
	@RequestMapping("/delMessage")
	public int delMessage(@RequestParam int id){
		int result=0;
		try{
			int result1=messageService.deleteMessageById(id);
			int commentCount=commentDao.getCommentCount(id);
			if(commentCount==0){//该留言没有评论
				if(result1==1){
					result=1;
				}
			}else{//该留言有评论
				int result2=commentService.deleteCommentByMsId(id);
				if(result1==1&&result2!=0){
					result=1;
				}
			}
		}catch(Exception e){
			e.getMessage();
		}
		return result;
	}
	
	@RequestMapping("/deleteMessages")
	public int deleteMulti(@RequestBody JSONArray jsonArray) throws Exception{
		int result=0;
		
		try{
			result=messageService.deleteMessages(jsonArray);
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		return result;
	}
	
	@RequestMapping("/addMessage")
	public int add(@RequestBody JSONObject jsonObject) throws Exception{
		int result=0;
		try{
			result=messageService.addMessage(jsonObject);
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		return result;
	}

}
